import React, { PureComponent } from 'react';
import { findDOMNode } from 'react-dom';
import { connect } from 'dva';
import {
  Menu,
  Card,
  Form,
  Input,
  Select,
  Col,
  Row,
  Button,
  Modal,
  Avatar,
  Dropdown,
  Icon,
  InputNumber,
  Radio,
} from 'antd';

import ButtonGroup from 'antd/lib/button/button-group';

import { Link, router } from 'umi';
import StandardTable from '@/components/StandardTable';
import Result from '@/components/Result';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import RadioGroup from 'antd/lib/radio/group';
import styles from './StudentList.less';

const FormItem = Form.Item;
const { Option } = Select;

// 所属专业
const specialities = {
  ch: '测绘',
  yg: '遥感',
  zh: '自环',
  cx: '城乡',
  dx: '地信',
  tg: '土管',
};

// 政治面貌
const politicalOutlooks = {
  partyMember: '中共党员',
  probationaryPartyMember: '中共预备党员',
  LeagueMember: '共青团员',
  masses: '群众',
};
const politicalOutlooksFilters = () =>
  Object.keys(politicalOutlooks).map(key => ({ text: politicalOutlooks[key], value: key }));

const UpdateForm = Form.create()(props => {
  const { updateModalVisible, current, updateDone, form, handleUpdate, handleUpdateDone, handleUpdateCancel } = props;
  const {
    form: { getFieldDecorator },
  } = props;

  const formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 13 },
  };

  const okHandler = e => {
    e.preventDefault()
    const id = current ? current.id : ''

    form.validateFields((err, fieldsValue) => {
      if (err) return

      form.resetFields()
      handleUpdate({id, ...fieldsValue})
    })
  }

  const getModalContent = () => {
    if (updateDone) {
      return (
        <Result
          type="success"
          title="操作成功"
          description="学生信息更新完成。"
          actions={
            <>
              <Button icon="eye" type="primary" onClick={() => { router.push(`/students/${current.key}`) }}>
                查看
              </Button>
              <Button icon="close" type="primary" onClick={handleUpdateDone}>
                关闭
              </Button>
            </>
          }
          className={styles.formResult}
        />
      );
    }

    return (
      <Form onSubmit={okHandler}>
        <FormItem label="姓名" {...formLayout}>
          {getFieldDecorator('name', {
            rules: [
              {
                required: true,
                message: '请先输入姓名',
              },
            ],
            initialValue: current.name,
          })(<Input placeholder="请输入姓名" />)}
        </FormItem>

        <FormItem label="年龄" {...formLayout}>
          {getFieldDecorator('age', {
            rules: [
              {
                required: true,
                message: '请先输入年龄',
              },
            ],
            initialValue: current.age,
          })(<InputNumber min={12} max={30} />)}
        </FormItem>

        <FormItem label="性别" {...formLayout}>
          {getFieldDecorator('sex', {
            rules: [
              {
                required: true,
                message: '请先输入性别',
              },
            ],
            initialValue: current.sex,
          })(
            <RadioGroup>
              <Radio value>男</Radio>
              <Radio value={false}>女</Radio>
            </RadioGroup>
          )}
        </FormItem>

        <FormItem label="班级" {...formLayout}>
          {getFieldDecorator('classes', {
            rules: [
              {
                required: true,
                message: '请先选择班级',
              },
            ],
            initialValue: current.classes,
          })(<InputNumber min={1} max={5} />)}
        </FormItem>
        <FormItem label="年级" {...formLayout}>
          {getFieldDecorator('grade', {
            rules: [
              {
                required: true,
                message: '请先选择年级',
              },
            ],
            initialValue: current.grade,
          })(
            <Select placeholder="请选择年级" style={{ width: '100%' }}>
              <Option value={2015}>2015级</Option>
              <Option value={2016}>2016级</Option>
              <Option value={2017}>2017级</Option>
              <Option value={2018}>2018级</Option>
            </Select>
          )}
        </FormItem>
        <FormItem label="专业" {...formLayout}>
          {getFieldDecorator('speciality', {
            rules: [
              {
                required: true,
                message: '请先选择专业',
              },
            ],
            initialValue: current.speciality,
          })(
            <Select placeholder="请选择专业" style={{ width: '100%' }}>
              {Object.keys(specialities).map(key => (
                <Option value={key} key={key}>
                  {specialities[key]}
                </Option>
              ))}
            </Select>
          )}
        </FormItem>

        <FormItem label="政治面貌" {...formLayout}>
          {getFieldDecorator('politicalOutlook', {
            rules: [
              {
                required: true,
                message: '请先选择政治面貌',
              },
            ],
            initialValue: current.politicalOutlook,
          })(
            <Select placeholder="请选择政治面貌" style={{ width: '100%' }}>
              {Object.keys(politicalOutlooks).map(key => (
                <Option value={key} key={key}>
                  {politicalOutlooks[key]}
                </Option>
              ))}
            </Select>
          )}
        </FormItem>
      </Form>
    );
  };

  const modalFooter = updateDone
    ? { footer: null, onCancel: handleUpdateDone }
    : { okText: '保存', onOk: okHandler, onCancel: handleUpdateCancel };

  return (
    <Modal
      distoryOnClose
      title="编辑"
      className={styles.standardListForm}
      width={640}
      bodyStyle={updateDone ? { padding: "72px 0" } : { padding: '28px 0 0' }}
      visible={updateModalVisible}
      {...modalFooter}
    >
      {getModalContent()}
    </Modal>
    )
});

@connect(({ students, loading }) => ({
  students,
  loading: loading.models.students,
}))
@Form.create()
class StudentList extends PureComponent {
  state = {
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    updateDone: false,
    current: {},
  };

  columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      onCell: () => ({
        style: {
          whiteSpace: 'noWrap',
          maxWidth: 80,
        },
      }),
      render: (text, record) => (
        <Link to={`/students/${record.key}`}>
          <Avatar
            style={{ top: -2, verticalAlign: 'middle', marginRight: 8 }}
            src={record.avatar}
            size="small"
          />
          {text}
        </Link>
      ),
    },
    {
      title: '学号',
      dataIndex: 'key',
    },
    {
      title: '专业',
      dataIndex: 'speciality',
      filters: [
        {
          text: specialities.ch,
          value: 'ch',
        },
        {
          text: specialities.yg,
          value: 'yg',
        },
        {
          text: specialities.zh,
          value: 'zh',
        },
        {
          text: specialities.cx,
          value: 'cx',
        },
        {
          text: specialities.dx,
          value: 'dx',
        },
        {
          text: specialities.tg,
          value: 'tg',
        },
      ],
      render: val => specialities[val],
    },
    {
      title: '班级',
      dataIndex: 'classes',
      sorter: true,
      needTotal: true,
    },
    {
      title: '年级',
      dataIndex: 'grade',
      sorter: true,
      needTotal: true,
    },
    {
      title: '政治面貌',
      dataIndex: 'politicalOutlook',
      filters: politicalOutlooksFilters(),
      render: value => politicalOutlooks[value],
    },
    {
      title: '绩点',
      dataIndex: 'gpa',
      sorter: true,
    },
    {
      title: '操作',
      render: (text, record) => (
        <ButtonGroup>
          <Button onClick={() => this.previewItem(record.key)}>
            <Icon type="eye" />
          </Button>
          <Button
            onClick={() => this.handleUpdateShow(record)}
            ref={component => {
                /* eslint-disable */
                this.addBtn = findDOMNode(component);
                /* eslint-enable */
              }}
          >
            <Icon type="edit" />
          </Button>
          <Button onClick={() => this.handleRemove(record.key)}>
            <Icon type="delete" />
          </Button>
        </ButtonGroup>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'students/fetch',
    });
  }

  previewItem = key => {
    router.push(`/students/${key}`);
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const getValue = obj =>
      Object.keys(obj)
        .map(key => obj[key])
        .join(',');

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);

      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'students/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();

    this.setState({
      formValues: {},
    });

    dispatch({
      type: 'students/fetch',
      payload: {},
    });
  };

  // 更多筛选
  toggleForm = () => {
    this.setState(val => ({
      expandForm: !val.expandForm,
    }));
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (selectedRows.length === 0) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'students/remove',
          payload: {
            key: selectedRows.map(row => row.key),
          },
          callback: () => {
            this.setState({
              selectedRows: {},
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      // TODO: 将 updateModal 独立出来 否则影响 其他部分

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'students/fetch',
        payload: values,
      });
    });
  };

  handleUpdate = fieldsValue => {
    const { dispatch} = this.props;
    const { formValues} = this.state

    setTimeout(() => this.addBtn.blur(), 0);
    dispatch({
      type: 'students/update',
      payload: {
        query: formValues,
        body: fieldsValue,
      },
      callback: () => {
        this.setState({ updateDone: true });
      },
    });
  };

  handleUpdateDone = () => {
    // setTimeout(() => this.addBtn.blur(), 0);
    this.setState({
      updateModalVisible: false,
    });
  };

  handleUpdateCancel = () => {
    setTimeout(() => this.addBtn.blur(), 0);
    this.setState({
      updateModalVisible: false,
    });
  };

  handleUpdateShow = record => {
    this.setState({
      updateModalVisible: true,
      current: record,
      updateDone: false,
    });
  };

  handleRemove = key => {
    const { dispatch } = this.props;
    dispatch({
      type: 'students/remove',
      payload: {
        key: [key],
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="年级">
              {getFieldDecorator('grade')(
                <Select placeholder="请选择年级" style={{ width: '100%' }}>
                  <Option value="2015">2015级</Option>
                  <Option value="2016">2016级</Option>
                  <Option value="2017">2017级</Option>
                  <Option value="2018">2018级</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="年级">
              {getFieldDecorator('grade')(
                <Select placeholder="请选择年级" style={{ width: '100%' }}>
                  <Option value={2015}>2015级</Option>
                  <Option value={2016}>2016级</Option>
                  <Option value={2017}>2017级</Option>
                  <Option value={2018}>2018级</Option>
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="专业">
              {getFieldDecorator('speciality')(
                <Select placeholder="请选择专业" style={{ width: '100%' }}>
                  {Object.keys(specialities).map(key => (
                    <Option value={key} key={key}>
                      {specialities[key]}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>

        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="班级">
              {getFieldDecorator('classes')(<InputNumber min={1} max={5} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="政治面貌">
              {getFieldDecorator('politicalOutlook')(
                <Select style={{ width: '100%' }}>
                  {Object.keys(politicalOutlooks).map(key => (
                    <Option key={key} value={key}>
                      {politicalOutlooks[key]}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>

        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      loading,
      students: { data },
    } = this.props;
    const { selectedRows, updateModalVisible, updateDone, current } = this.state;

    const updateParentMethods = {
      handleUpdate: this.handleUpdate,
      handleUpdateDone: this.handleUpdateDone,
      handleUpdateCancel: this.handleUpdateCancel,
      updateModalVisible,
      updateDone,
      current
    };

    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    return (
      <PageHeaderWrapper title="学生列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button
                icon="plus"
                type="primary"
                onClick={() => {
                  router.push('/students/create');
                }}
              >
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button>批量操作</Button>
                  <Dropdown overlay={menu}>
                    <Button>
                      更多操作 <Icon type="down" />
                    </Button>
                  </Dropdown>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <UpdateForm {...updateParentMethods} />
      </PageHeaderWrapper>
    );
  }
}

export default StudentList;
